package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.RegionQuery;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void insert(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public Region select(String id) {
        return regionRepository.findById(id).get();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        Query query = new Query();

        //查询总记录数
        long total = mongoTemplate.count(query, Region.class);
        if (total == 0) {
            return Page.empty();
        }

        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize()
                , Sort.Direction.DESC, "_id");
        query.with(pageable);

        List<Region> list = mongoTemplate.find(query, Region.class, "destination_region");

        System.out.println(list);

        return new PageImpl<Region>(list, pageable, total);
    }

    @Override
    public void changeHotValue(String id, int hot) {
        Region region = this.select(id);
        region.setIshot(hot);
        this.update(region);
    }

    @Override
    public List<Region> listAll() {
        //必须热门
        //排序
        return regionRepository.findByIshotOrderBySequenceAsc(Region.STATE_HOT);
    }
}
